package com.atguigu.eduservice.service.impl;

import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.mapper.EduVideoMapper;
import com.atguigu.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author wangshuai
 * @since 2021-02-04
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private  VodClient vodClient;

    @Override
    public List<EduVideo> getVideoListById(String chapterId) {

        QueryWrapper<EduVideo> wrapperVdieo = new QueryWrapper<>();
        wrapperVdieo.eq("chapter_id",chapterId);
        List<EduVideo> eduVideoList = baseMapper.selectList(wrapperVdieo);

        return eduVideoList;
    }

    @Override
    public boolean removeByCourseId(String courseId) {
        //根据课程id查询所有video
        QueryWrapper<EduVideo> wrapperVideo = new QueryWrapper<>();
        wrapperVideo.eq("course_id",courseId);
        wrapperVideo.select("video_source_id");
        List<EduVideo> eduVideoList = baseMapper.selectList(wrapperVideo);

        List<String> videoIdList = new ArrayList<>();

        for (int i = 0; i < eduVideoList.size(); i++) {
            EduVideo eduVideo = eduVideoList.get(i);
            String videoSourceId = eduVideo.getVideoSourceId();

            if (!StringUtils.isEmpty(videoSourceId)) {
                videoIdList.add(videoSourceId);
            }
        }

        if(videoIdList.size() > 0) {
            vodClient.deleteBatch(videoIdList);
        }

        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();

        wrapper.eq("course_id",courseId);

        Integer count = baseMapper.delete(wrapper);

        return count > 0 && count != null;
    }
}
